#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int rd() {
    int s=0,m=0;char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')m=1;ch=getchar();}
    while( isdigit(ch)) s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
    return m?-s:s;
}
const int inf=1e18;
double t,delt,eps=1e-15;
int n,k,a[105],b[105],num[105],sz[105],fl[105],ans=inf;
int bel[105],mp[105][105],Mx[105],Mn[105];
int lf=inf;
int f() {
    int sum=0;for(int i=1;i<=k;i++) Mx[i]=-inf,Mn[i]=inf;
    for(int i=1;i<=n;i++) {
        Mx[bel[i]]=max(Mx[bel[i]],a[i]);
        Mn[bel[i]]=min(Mn[bel[i]],a[i]);
    }
    for(int i=1;i<=k;i++) sum+=b[Mx[i]]-b[Mn[i]];
    return sum;
}
int upd(int x,int y) {
    int bx=bel[x],by=bel[y];
    if(bx==by||a[x]==a[y]||mp[bx][a[y]]||mp[by][a[x]]) return 0;
    mp[bx][a[x]]--,mp[bx][a[y]]++,mp[by][a[y]]--,mp[by][a[x]]++;
    bel[x]=by,bel[y]=bx;
    return 1;
}
void solve(int fl) {
	if(fl) srand(rand()*rand()+rand());
    t=100000,delt=0.99987654321,lf=f();
	while(t>eps) {
		int x=rand()%n+1,y=rand()%n+1;
        while((!upd(x,y))) x=rand()%n+1,y=rand()%n+1;
		int nf=f(),delf=nf-lf;
		if(delf<0) lf=nf;
		else if(exp(-delf/t)*RAND_MAX<1.0*rand()) upd(x,y);
		t*=delt;
	}
	ans=min(ans,lf);
}
signed main(){
    freopen("diyiti.in","r",stdin);freopen("diyiti.out","w",stdout);
    srand(823811717);
    cin>>n>>k;
    for(int i=1;i<=n;i++) a[i]=b[i]=rd();
    sort(b+1,b+n+1);int nn=unique(b+1,b+n+1)-b-1;
    for(int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+nn+1,a[i])-b,num[a[i]]++;
    while(1) {
        int maxn=-inf,id=-1;
        for(int i=1;i<=n;i++) if(num[i]>0&&num[i]>maxn) maxn=num[i],id=i;
        if(id==-1) break;
        while(num[id]--) {
            int minn=inf,ii=-1,jj=-1;
            for(int i=1;i<=n;i++) if(!fl[i]&&a[i]==id) ii=i;
            for(int i=1;i<=k;i++) if(sz[i]<minn&&!mp[i][id]) minn=sz[i],jj=i;
            if(jj==-1) return puts("-1"),0;
            fl[ii]=1,sz[jj]++,bel[ii]=jj,mp[jj][a[ii]]=1;
        }
    }
    for(int i=1;i<=k;i++) if(sz[k]!=n/k) return puts("-1"),0;
    for(int i=1;i<=10;i++) solve(0);
    cout<<ans;
    return 0;
}